package org.lpw.wormhole.util;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.protocol.HttpContext;

/**
 * @author lpw
 */
public class HttpGzipInterceptor
    implements HttpRequestInterceptor, HttpResponseInterceptor
{
    private static final String[] ACCEPT_ENCODING = {"Accept-Encoding", "gzip"};

    @Override
    public void process(HttpRequest request, HttpContext context)
        throws HttpException, IOException
    {
        if(!request.containsHeader(ACCEPT_ENCODING[0]))
        {
            request.addHeader(ACCEPT_ENCODING[0], ACCEPT_ENCODING[1]);
        }
    }

    @Override
    public void process(HttpResponse response, HttpContext context)
        throws HttpException, IOException
    {
        HttpEntity entity = response.getEntity();
        Header header = entity.getContentEncoding();
        if(header!=null)
        {
            HeaderElement[] codecs = header.getElements();
            for(int i = 0; i<codecs.length; i++)
            {
                if(codecs[i].getName().equalsIgnoreCase(ACCEPT_ENCODING[1]))
                {
                    response.setEntity(new HttpGzipEntityWrapper(entity));

                    return;
                }
            }
        }
    }
}
